#include "StdAfx.h"
#include "Csocket.h"
#include <process.h>
#include <iostream>
#include "..\ChatServer\Message.h"


using namespace std;

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

DWORD IOthread = 0;

Csocket::Csocket(void)
{
}

Csocket::~Csocket(void)
{
}

int connectserver(char* servname)
{
	WSADATA wsaData;
	SOCKET ConnectSocket = INVALID_SOCKET;
	struct addrinfo *result = NULL,
		*ptr = NULL,
		hints;


	int iResult;

	// Initialize Winsock
	iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if (iResult != 0) {
		printf("WSAStartup failed with error: %d\n", iResult);
		return 1;
	}

	ZeroMemory( &hints, sizeof(hints) );
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	// Resolve the server address and port
	iResult = getaddrinfo(servname, DEFAULT_PORT, &hints, &result);
	if ( iResult != 0 ) {
		printf("getaddrinfo failed with error: %d\n", iResult);
		WSACleanup();
		return 1;
	}

	// Attempt to connect to an address until one succeeds
	for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

		// Create a SOCKET for connecting to server
		ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
			ptr->ai_protocol);
		if (ConnectSocket == INVALID_SOCKET) {
			printf("socket failed with error: %ld\n", WSAGetLastError());
			WSACleanup();
			return 1;
		}

		// Connect to server.
		iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
		if (iResult == SOCKET_ERROR) {
			closesocket(ConnectSocket);
			ConnectSocket = INVALID_SOCKET;
			continue;
		}
		IOthread = _beginthread((void( *)(void *))messagefunc,0,(void*)ConnectSocket);
		if (IOthread<0)
		{
			cout<<"_beginthread error!"<<"\n";
		}
		break;
	}

	if(ConnectSocket == INVALID_SOCKET)
	{
		return 1;

	}

	freeaddrinfo(result);
	return 0;
}

int messagefunc( void* asocket )
{
	SOCKET ConnectSocket = (SOCKET)asocket;

	int iResult;
	// Send an initial buffer

	char *sendbuf = "this is a test";

	char recvbuf[DEFAULT_BUFLEN];
	int recvbuflen = DEFAULT_BUFLEN;

	CT_MSG_login logmsg;

	iResult = send( ConnectSocket, (const char *)&logmsg, sizeof(CT_MSG_login), 0 );
	if (iResult == SOCKET_ERROR) {
		printf("send failed with error: %d\n", WSAGetLastError());
		closesocket(ConnectSocket);
		WSACleanup();
		return 1;
	}


	printf("Hello Bytes Sent: %ld\n", iResult);

	do {
		 
		iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
		if ( iResult > 0 )
		{

			CT_MSG* pMsgHeader = (CT_MSG*)recvbuf;

			switch (pMsgHeader->msg)
			{
			case CT_MSG::UN: 

				break;
			case CT_MSG::S2C:    
				{
					CT_MSG_S2C * S2C = (CT_MSG_S2C * )pMsgHeader;
					cout<<"server:"<<S2C->str<<endl;
				}
				break;	
			case CT_MSG::SPEAK:    

				break;
			default:

				printf("unknown msg.\n");
			}
			//printf("Bytes received: %d\n", iResult);
		}
		else if ( iResult == 0 )
			printf("Connection closed\n");
		else
			printf("recv failed with error: %d\n", WSAGetLastError());

		CT_MSG unMsg;
		iResult = send( ConnectSocket, (const char *)&unMsg, sizeof(CT_MSG), 0 );
		if (iResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ConnectSocket);
			WSACleanup();
			return 1;
		}

	} while( iResult > 0 );



	// cleanup
	closesocket(ConnectSocket);
	WSACleanup();
	return 0;
}
